package com.qidian.zl.paper.service.impl;

import com.qidian.zl.paper.dao.AdminDAO;
import com.qidian.zl.paper.factory.DAOFactory;
import com.qidian.zl.paper.pojo.Admin;
import com.qidian.zl.paper.service.AdminService;
import com.qidian.zl.paper.util.MD5Utils;
import com.qidian.zl.paper.util.StResult;

public class AdminServiceImpl implements AdminService {
    private AdminDAO adminDAO = DAOFactory.getUserDAO();

    @Override
    public StResult queryByPage(int page, int size, Admin admin) {
        StResult  stResult=StResult.ok();

        stResult.setObj(adminDAO.queryTotal(admin));
        stResult.setData(adminDAO.queryByPage(page,size,admin));
        return stResult;
    }

    /**
     *
     * @param admin
     * @return 1成功 2 重复
     */
    @Override
    public int save(Admin admin) {
        int result=0;
        Admin a=adminDAO.queryByName(admin.getAdminName());
        if (a!=null){
            return 2;
        }
        //给密码加密
        String adminPass=admin.getAdminPass();
        admin.setAdminPass(adminPass);

        return adminDAO.save(admin);
    }

    @Override
    public Admin login(String adminName, String adminPass) {
        Admin admin=adminDAO.queryByName(adminName);
        if (admin==null){
            //登录失败
            return null;
        }
        //密码相同 登录成功
        adminPass= MD5Utils.stringToMD5(adminPass);
        if (admin.getAdminPass().endsWith(adminPass)){
            return admin;
        }
        return null;
    }

    @Override
    public int update(Admin admin) {
        Admin abyId = adminDAO.queryById(admin.getAdminId());
        Admin abyName = adminDAO.queryByName(admin.getAdminName());
        if(abyName!=null && !abyId.getAdminId().equals(abyName.getAdminId())){
            return 2;// 登录名重复
            }
        if (admin.getAdminPass()!=null&& !admin.getAdminPass().equals("")){
            String adminPass=admin.getAdminPass();
            adminPass=MD5Utils.stringToMD5(adminPass);
            admin.setAdminPass(adminPass);
        }else {
            admin.setAdminPass(abyId.getAdminPass());
        }
        return adminDAO.update(admin);
    }

    @Override
    public Admin queryById(long adminId) {
        return adminDAO.queryById(adminId);
    }
}
